package net.atomarrow.util;

import java.util.HashSet;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
 * Gson工具类
 * @author Michael
 *
 */
public class GsonUtil {

    private static final Gson gson = new Gson();

    public static String toJson(Object obj) {
        return gson.toJson(obj);
    }

    public static String toJsonWith(Object obj, String... param) {
        Gson gson = new GsonBuilder().setExclusionStrategies(
                new myExclusionStrategy(false, param)).create();
        return gson.toJson(obj);
    }

    public static String toJsonWithOut(Object obj, String... param) {
        Gson gson = new GsonBuilder().setExclusionStrategies(
                new myExclusionStrategy(true, param)).create();
        return gson.toJson(obj);
    }

}

class myExclusionStrategy implements ExclusionStrategy {

    private final boolean isSkipMode;
    private final HashSet<String> paramSet;

    public myExclusionStrategy(boolean isSkipMode, String... param) {
        this.isSkipMode = isSkipMode;
        paramSet = new HashSet<String>();
        for (int i = 0; i < param.length; i++) {
            paramSet.add(param[i]);
        }
    }

    @Override
    public boolean shouldSkipClass(Class<?> arg0) {
        return false;
    }

    @Override
    public boolean shouldSkipField(FieldAttributes field) {
        if (isSkipMode) {
            return paramSet.contains(field.getName());
        } else {
            return !paramSet.contains(field.getName());
        }
    }

}
